package com.qianli.user.application;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.common.utils.DateUtil;
import com.fqgj.xjd.user.dao.UserThirdPartDao;
import com.fqgj.xjd.user.entity.UserThirdPartEntity;
import com.google.common.collect.Lists;
import com.qianli.user.UserHeadRequest;
import com.qianli.user.domain.enums.FaceRecognitionStatusEnum;
import com.qianli.user.domain.enums.UserAuthStatusEnum;
import com.qianli.user.domain.enums.UserModelItemStatusEnum;
import com.qianli.user.domain.enums.ZmCreditStatusEnum;
import com.qianli.user.domain.facatory.UserAuthFactory;
import com.qianli.user.domain.model.UserAuthModel;
import com.qianli.user.domain.model.auth.*;
import com.qianli.user.enums.CreditAuthTypeEnum;
import com.qianli.user.enums.CreditCardBillShowStatusEnum;
import com.qianli.user.enums.FrozenCodeEnum;
import com.qianli.user.enums.ThirdPartLoginTypeEnum;
import com.qianli.user.ro.UserStateCode;
import com.qianli.user.ro.auth.*;
import com.qianli.user.ro.auth.cancel.CreditCardCancelRO;
import com.qianli.user.ro.auth.comfirm.*;
import com.qianli.user.ro.auth.submit.*;
import com.qianli.user.service.UserAuthService;
import com.qianli.user.service.UserConfigService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * name:用户认证信息
 * auth:ting.li@qianli-inc.com
 * date:2018/1/2 21:10
 * version: v1.0.0
 **/
@Service
public class UserAuthApplication extends UserAbstractApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthApplication.class);

    @Autowired
    private UserAuthFactory userAuthFactory;
    @Autowired
    private UserConfigService userConfigService;
    @Autowired
    private UserFrozenApplication userFrozenApplication;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private UserThirdPartDao userThirdPartDao;

    /**
     * 人脸识别信审
     *
     * @param userAuthFace
     * @return
     */
    public Response<Boolean> auditAuthFaceRecognition(UserAuthFaceRO userAuthFace) {
        //加载模型
        UserAuthModel userAuthModel = new UserAuthModel();
        userAuthModel.setUserCode(userAuthFace.getUserCode());
        userAuthFactory.load(userAuthModel);

        UserAuthModel newUm = new UserAuthModel();
        newUm.setUserCode(userAuthFace.getUserCode());
        //人脸识别不存在
        if (CollectionUtils.isEmpty(userAuthModel.getAuthFaceRecognitions())) {
            return Response.error(UserStateCode.USER_FACE_RECOGNITION_NOT_EXISTS);
        }
        UserAuthFaceRecognition recognition = userAuthModel.getAuthFaceRecognitions().get(0);
        if (!recognition.getAuthorized()) {
            return Response.error(UserStateCode.USER_FACE_RECOGNITION_STATUS_NOT_MATCH, "人脸识别未通过，不可拒绝");
        }
        if (!userAuthFace.getFaceFailReasonTypeEnum().getType().equals(recognition.getType())) {
            return Response.error(UserStateCode.USER_FACE_RECOGNITION_TYPE_NOT_MATCH);
        }
        recognition.setPassed(0);
        newUm.setAuthFaceRecognitions(Lists.newArrayList(recognition));
        //存储模型
        userAuthFactory.store(newUm);
        return Response.ok();

    }

    public Response<UserAuthInfoRO> load(String userCode, Integer authType) {
        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
        Response<UserAuthInfoRO> response = load(userCode);
        UserAuthInfoRO authInfoRO = response.getData();
        UserAuthInfoRO result = new UserAuthInfoRO();
        result.setUserCode(userCode);
        result.setBiz(biz);
        result.setAppCode(appCode);
        switch (authType) {
            case 1://芝麻
                result.setZmCredit(authInfoRO.getZmCredit());
                break;
            case 2://银行卡
                result.setBankCredits(authInfoRO.getBankCredits());
                break;
            case 3://人脸识别
                result.setAuthFaceRecognitions(authInfoRO.getAuthFaceRecognitions());
                break;
            case 4://支付宝
                result.setAuthAlipay(authInfoRO.getAuthAlipay());
                break;
            case 5://信用卡
                result.setCreditCardROS(authInfoRO.getCreditCardROS());
                break;
            case 6://淘宝
                result.setAuthTaobao(authInfoRO.getAuthTaobao());
                break;
            case 7://运营商
                result.setUserAuthCarrier(authInfoRO.getUserAuthCarrier());
                break;
            case 8://京东
                break;
            case 9://社保
                break;
            case 10://公积金
                break;
            case 11://学信
                break;
            default:
                break;
        }
        return Response.ok(result);
    }

    /**
     * 认证信息查询
     *
     * @param userCode
     * @return
     */
    public Response<UserAuthInfoRO> load(String userCode) {
        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
        //加载认证信息
        UserAuthModel userAuth = new UserAuthModel();
        userAuth.setUserCode(userCode);
        userAuthFactory.load(userAuth);
        //认证转换
        UserAuthInfoRO userAuthInfoRO = new UserAuthInfoRO();
        userAuthInfoRO.setUserCode(userCode);
        userAuthInfoRO.setBiz(biz);
        userAuthInfoRO.setAppCode(appCode);
        //实名信息
        if (null != userAuth.getCustomer()) {
            CustomerRO customer = new CustomerRO();
            BeanUtils.copyProperties(userAuth.getCustomer(), customer);
            userAuthInfoRO.setCustomer(customer);
        }
        //ZM信息
        if (null != userAuth.getZmCredit()) {
            ZMCreditRO zmCreditRO = new ZMCreditRO();
            BeanUtils.copyProperties(userAuth.getZmCredit(), zmCreditRO);
            userAuthInfoRO.setZmCredit(zmCreditRO);
        }
        //银行卡
        if (CollectionUtils.isNotEmpty(userAuth.getBankCredits())) {
            List<BankCreditRO> bankCreditROs = Lists.newArrayList();
            for (BankCredit bc : userAuth.getBankCredits()) {
                BankCreditRO bankCreditRO = new BankCreditRO();
                BeanUtils.copyProperties(bc, bankCreditRO);
                bankCreditROs.add(bankCreditRO);
            }
            userAuthInfoRO.setBankCredits(bankCreditROs);
        }
        //人脸识别
        if (CollectionUtils.isNotEmpty(userAuth.getAuthFaceRecognitions())) {

            List<UserAuthFaceRecognitionRO> faceRecognitionROs = Lists.newArrayList();
            for (UserAuthFaceRecognition faceRecognition : userAuth.getAuthFaceRecognitions()) {
                UserAuthFaceRecognitionRO faceRecognitionRO = new UserAuthFaceRecognitionRO();
                BeanUtils.copyProperties(faceRecognition, faceRecognitionRO);
                faceRecognitionROs.add(faceRecognitionRO);
            }
            userAuthInfoRO.setAuthFaceRecognitions(faceRecognitionROs);
        }

        return Response.ok(userAuthInfoRO);
    }

    /**
     * 信用卡处理
     *
     * @param creditCards
     * @return
     */
//    private List<CreditCardRO> dealCreditCards(List<CreditCard> creditCards) {
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        List<CreditCardRO> creditCardROS = Lists.newArrayList();
//        for (CreditCard cc : creditCards) {
//            CreditCardRO cr = new CreditCardRO();
//            cr.setUserCode(cc.getUserCode());
//            cr.setBankName(cc.getBankName());
//            cr.setBankKey(cc.getBankKey());
//            //银行卡取后四位
//            if (CollectionUtils.isNotEmpty(cc.getNumbers())) {
//                List<String> newNumList = Lists.newArrayList();
//                for (String num : cc.getNumbers()) {
//                    newNumList.add(num.substring(num.length() - 4, num.length()));
//                }
//                cr.setNumbers(newNumList);
//            }
//            CreditCardAccount account = cc.getAccount();
//            CreditCardAccountRO accountRO = new CreditCardAccountRO();
//            BeanUtils.copyProperties(account, accountRO);
//            cr.setAccount(accountRO);
//            cr.setTaskId(cc.getTaskId());
//            Integer showStatus = CreditCardBillShowStatusEnum.IMPORTED.getType();
//            //初始化，也就是认证中
//            if (cc.getStatus().equals(UserAuthStatusEnum.INIT.getStatus())) {
//                showStatus = CreditCardBillShowStatusEnum.IMPORTING.getType();
//            }
//            //导入失败
//            if (cc.getStatus().equals(UserAuthStatusEnum.FAIL.getStatus())) {
//                showStatus = CreditCardBillShowStatusEnum.FAIL.getType();
//            }
//            //取消
//            if (cc.getStatus().equals(UserAuthStatusEnum.CANCEL.getStatus())) {
//                showStatus = CreditCardBillShowStatusEnum.CANCELED.getType();
//            }
//            //导入成功
//            if (cc.getStatus().equals(UserAuthStatusEnum.AUTHORIZED.getStatus())) {
//                //无账单
//                if (CollectionUtils.isEmpty(cc.getBills()) || !cc.getBills().get(0).getTaskId().equals(cc.getTaskId())) {
//                    showStatus = CreditCardBillShowStatusEnum.NO_BILL.getType();
//                } else {
//                    CreditCardBill bill = cc.getBills().get(0);
//                    Integer expireDays = userConfigService.queryCreditCardBillExpiredDay(appCode, biz);
//                    if (DateUtil.afterDiffDay(new Date(), bill.getGmtModified(), expireDays)) {
//                        showStatus = CreditCardBillShowStatusEnum.EXPIRED.getType();
//                    }
//                }
//            }
//            cr.setShowStatus(showStatus);
//            creditCardROS.add(cr);
//        }
//        return creditCardROS;
//    }

    /**
     * Google认证确认
     *
     * @param googleAuthConfirm
     * @param oldUm
     * @param newUm
     * @param authorized
     * @return
     */
    private Response<Boolean> checkGoogleConfirmStatus(GoogleAuthConfirmRO googleAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm, Boolean authorized) {
        UserAuthGoogle newUa = new UserAuthGoogle();
        BeanUtils.copyProperties(googleAuthConfirm, newUa);
        UserAuthGoogle oldUa = oldUm.getUserAuthGoogle();
        if (null == oldUa) {
            newUa.setItemStatus(UserModelItemStatusEnum.ADD.getType());
        } else {
            newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
            newUa.setId(oldUa.getId());
        }
        newUa.setAuthorized(authorized);
        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
        newUm.setUserAuthGoogle(newUa);
        return Response.ok(true);
    }

    /**
     * Twitter认证确认
     *
     * @param twitterAuthConfirm
     * @param oldUm
     * @param newUm
     * @param authorized
     * @return
     */
    private Response<Boolean> checkTwitterConfirmStatus(TwitterAuthConfirmRO twitterAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm, Boolean authorized) {
        UserAuthTwitter newUa = new UserAuthTwitter();
        BeanUtils.copyProperties(twitterAuthConfirm, newUa);
        UserAuthTwitter oldUa = oldUm.getUserAuthTwitter();
        if (null == oldUa) {
            newUa.setItemStatus(UserModelItemStatusEnum.ADD.getType());
        } else {
            newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
            newUa.setId(oldUa.getId());
        }
        newUa.setAuthorized(authorized);
        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
        newUm.setUserAuthTwitter(newUa);
        return Response.ok(true);
    }


    /**
     * Facebook认证确认
     *
     * @param facebookAuthConfirm
     * @param oldUm
     * @param newUm
     * @param authorized
     * @return
     */
    private Response<Boolean> checkFacebookConfirmStatus(FacebookAuthConfirmRO facebookAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm, Boolean authorized) {
        //openId 是否 绑定过其他的用户
        UserThirdPartEntity userThirdPartEntity = userThirdPartDao.selectOneByOpenId(facebookAuthConfirm.getOpenId());
        LOGGER.info("=== checkFacebookConfirmStatus ===,useCode：{},userThirdPartEntity:{}", oldUm.getUserCode(), JSON.toJSONString(userThirdPartEntity));
        //已经绑定过其他用户
        if (userThirdPartEntity != null && !userThirdPartEntity.getUserCode().equals(oldUm.getUserCode())) {
            return Response.error(UserStateCode.USER_SOCIAL_HAS_BEEN_BOUND);
        }
        //没有绑定过
        if (userThirdPartEntity == null) {
            // 存储open_id 和user_code的对应关系
            UserThirdPartEntity userThirdPartEntityNew = new UserThirdPartEntity()
                    .setUserCode(oldUm.getUserCode())
                    .setOpenId(facebookAuthConfirm.getOpenId())
                    .setOrigin(ThirdPartLoginTypeEnum.FACEBOOK.name());
            userThirdPartDao.insertWithCustomId(userThirdPartEntityNew);
        }
        UserAuthFacebook newUa = new UserAuthFacebook();
        BeanUtils.copyProperties(facebookAuthConfirm, newUa);
        UserAuthFacebook oldUa = oldUm.getUserAuthFacebook();
        if (null == oldUa) {
            newUa.setItemStatus(UserModelItemStatusEnum.ADD.getType());
        } else {
            newUa.setId(oldUa.getId());
            newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
        }
        newUa.setAuthorized(authorized);
        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
        newUm.setUserAuthFacebook(newUa);
        return Response.ok(true);
    }

    /**
     * 信用卡认证确认
     *
     * @param creditCardConfirm
     * @param oldUm
     * @param newUm
     * @param authorized
     * @return
     */
//    private Response<Boolean> checkCreditCardConfirmStatus(CreditCardConfirmRO creditCardConfirm, UserAuthModel oldUm, UserAuthModel newUm,
//                                                           Boolean authorized) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        creditCardConfirm.setUserCode(userCode);
//        CreditCard newUa = new CreditCard();
//        newUa.setUserCode(userCode);
//        convertCreditCardConfirmRO2Model(creditCardConfirm, newUa, authorized);
//        //找到之前提交的认证数据
//        List<CreditCard> creditCards = oldUm.getCreditCards();
//        CreditCard oldUa = null;
//        if (CollectionUtils.isNotEmpty(creditCards)) {
//            for (CreditCard cc : creditCards) {
//                if (cc.getBankKey().equals(creditCardConfirm.getBankKey())) {
//                    oldUa = cc;
//                }
//            }
//        }
//        if (null == oldUa) {
//            return Response.error(UserStateCode.USER_AUTH_CREDITCARD_NOT_EXISTS);
//        }
//        Integer maxDailyAlipayTime = userConfigService.queryMaxDailyCreditCardTime(appCode, biz);
//        //获取今日信用卡认证次数
//        Integer userAlipayTime = redisUtils.getObject("USER_AUTH_CREDITCARD_DAILY_TIME" + userCode, Integer.class);
//        //信用卡超过限制
//        if (null != userAlipayTime && userAlipayTime > maxDailyAlipayTime) {
//            return Response.error(UserStateCode.USER_AUTH_CREDITCARD_OVER_TIME);
//        }
//        //设置更新状态
//        newUa.setId(oldUa.getId());
//        newUa.setAuthorized(authorized);
//        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
//        newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
//        newUa.setAccount(oldUa.getAccount());
//        newUm.setCreditCards(Lists.newArrayList(newUa));
//        return Response.ok(true);
//    }

    /**
     * 信用卡确认
     *
     * @param creditCardConfirm
     * @param newUa
     */
    private void convertCreditCardConfirmRO2Model(CreditCardConfirmRO creditCardConfirm, CreditCard newUa, Boolean authorized) {
        newUa.setBankName(creditCardConfirm.getBankName());
        newUa.setBankKey(creditCardConfirm.getBankKey());
        newUa.setNumbers(creditCardConfirm.getNumbers());
        newUa.setTaskId(creditCardConfirm.getTaskId());
        newUa.setOrignalStatus(creditCardConfirm.getOrignalStatus());
        //无账单
        if (null == creditCardConfirm.getDataUrl()) {
            return;
        }
        //有账单
        List<CreditCardBill> bills = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(creditCardConfirm.getNumbers())) {
            for (String number : creditCardConfirm.getNumbers()) {
                CreditCardBill bill = new CreditCardBill();
                bill.setUserCode(newUa.getUserCode());
                bill.setBankName(creditCardConfirm.getBankName());
                bill.setBankKey(creditCardConfirm.getBankKey());
                bill.setNumber(number);
                bill.setDataUrl(creditCardConfirm.getDataUrl());
                bill.setTaskId(creditCardConfirm.getTaskId());
                bill.setStatus(authorized ? 1 : 0);
                bills.add(bill);
            }
        }
        newUa.setBills(bills);

    }

    /**
     * 运营商认证确认
     *
     * @param carrierAuthConfirm
     * @param oldUm
     * @param newUm
     * @return
     */
    private Response<Boolean> checkCarrierConfirmStatus(CarrierAuthConfirmRO carrierAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm,
                                                        Boolean authorized) {
        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
        carrierAuthConfirm.setUserCode(userCode);
        UserAuthCarrier newUc = new UserAuthCarrier();
        BeanUtils.copyProperties(carrierAuthConfirm, newUc);

        UserAuthCarrier oldUc = oldUm.getUserAuthCarrier();
        if (null == oldUc) {
            return Response.error(UserStateCode.USER_CARRIER_NOT_EXISTS);
        }
        newUc.setId(oldUc.getId());
        newUc.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
        newUc.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
        newUm.setUserAuthCarrier(newUc);
        return Response.ok(true);

    }

    /**
     * 淘宝认证确认
     *
     * @param taobaoAuthConfirm
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<Boolean> checkTaobaoConfirmStatus(TaobaoAuthConfirmRO taobaoAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm,
//                                                       Boolean authorized) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        taobaoAuthConfirm.setUserCode(userCode);
//        UserAuthTaobao newUa = new UserAuthTaobao();
//        BeanUtils.copyProperties(taobaoAuthConfirm, newUa);
//
//        UserAuthTaobao oldUa = oldUm.getAuthTaobao();
//        Integer maxDailyAuthTaobaoTime = userConfigService.queryMaxDailyAuthTaobaoTime(appCode, biz);
//        //获取今日支付宝认证次数
//        Integer userTaobaoTime = redisUtils.getObject("USER_AUTH_TAOBAO_DAILY_TIME" + userCode, Integer.class);
//        //人脸识别超过限制
//        if (null != userTaobaoTime && userTaobaoTime > maxDailyAuthTaobaoTime) {
//            return Response.error(UserStateCode.USER_AUTH_ALIPAY_OVER_TIME);
//        }
//        //设置更新状态
//        newUa.setId(oldUa.getId());
//        newUa.setAuthorized(authorized);
//        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
//        newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
//        newUm.setAuthTaobao(newUa);
//        return Response.ok(true);
//    }

    /**
     * 支付宝认证确认
     *
     * @param alipayAuthConfirm
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<Boolean> checkAlipayConfirmStatus(AlipayAuthConfirmRO alipayAuthConfirm, UserAuthModel oldUm, UserAuthModel newUm,
//                                                       Boolean authorized) {
//
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        alipayAuthConfirm.setUserCode(userCode);
//        UserAuthAlipay newUa = new UserAuthAlipay();
//        BeanUtils.copyProperties(alipayAuthConfirm, newUa);
//
//        UserAuthAlipay oldUa = oldUm.getAuthAlipay();
//
//        Integer maxDailyAlipayTime = userConfigService.queryMaxDailyAuthAlipayTime(appCode, biz);
//        //获取今日支付宝认证次数
//        Integer userAlipayTime = redisUtils.getObject("USER_AUTH_ALIPAY_DAILY_TIME" + userCode, Integer.class);
//        //支付宝认证超过限制
//        if (null != userAlipayTime && userAlipayTime > maxDailyAlipayTime) {
//            return Response.error(UserStateCode.USER_AUTH_ALIPAY_OVER_TIME);
//        }
//        //设置更新状态
//        newUa.setId(oldUa.getId());
//        newUa.setAuthorized(authorized);
//        newUa.setStatus(authorized ? UserAuthStatusEnum.AUTHORIZED.getStatus() : UserAuthStatusEnum.FAIL.getStatus());
//        newUa.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
//        newUm.setAuthAlipay(newUa);
//        return Response.ok(true);
//    }
//
//    /**
//     * 人脸识别
//     * 只存在一条有效
//     *
//     * @param faceRecognitionConfirm
//     * @param oldUm
//     * @param newUm
//     * @return
//     */
//    private Response<Boolean> checkFaceRecognitionConfirmStatus(FaceRecognitionConfirmRO faceRecognitionConfirm,
//                                                                UserAuthModel oldUm, UserAuthModel newUm, Boolean authorized) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        faceRecognitionConfirm.setUserCode(userCode);
//        List<UserAuthFaceRecognition> faceRecognitions = oldUm.getAuthFaceRecognitions();
//        if (CollectionUtils.isEmpty(faceRecognitions)) {
//            return Response.error(UserStateCode.USER_FACE_RECOGNITION_NOT_EXISTS);
//        }
//        UserAuthFaceRecognition newFaceRecog = null;
//        for (UserAuthFaceRecognition face : faceRecognitions) {
//            if (faceRecognitionConfirm.getType().equals(face.getType())) {
//                newFaceRecog = face;
//            }
//        }
//        if (null == newFaceRecog) {
//            return Response.error(UserStateCode.USER_FACE_RECOGNITION_NOT_EXISTS);
//        }
//        //fail history
//        if (!authorized) {
//            UserAuthFaceRecognitionHistory failHistory = new UserAuthFaceRecognitionHistory();
//            BeanUtils.copyProperties(faceRecognitionConfirm.getFaceRecognitionFailConfirm(), failHistory);
//            failHistory.setItemStatus(UserModelItemStatusEnum.ADD.getType());
//            newFaceRecog.setFailHistory(failHistory);
//        }
//
//        //查询是否处于人脸识别冷冻
//        Response<Boolean> isFrozenResponse = userFrozenApplication.isFrozen(userCode,
//                FrozenCodeEnum.FACE_RECONGNITION, null);
//        if (isFrozenResponse.isSuccess() && isFrozenResponse.getData()) {
//            return Response.error(UserStateCode.USER_FROZEN_FACE);
//        }
//        //查询该用户每天可人脸识别总次数
//        Integer maxDailyAuthFaceTime = userConfigService.queryMaxDailyAuthFaceTime(appCode, biz);
//        Integer userFaceTime = redisUtils.getObject("USER_AUTH_FACE_DAILY_TIME" + userCode, Integer.class);
//        //人脸识别超过限制
//        if (null != userFaceTime && userFaceTime >= maxDailyAuthFaceTime) {
//            return Response.error(UserStateCode.USER_AUTH_FACE_OVER_TIME);
//        }
//        newFaceRecog.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
//        //识别通过
//        if (authorized) {
//            newFaceRecog.setPassed(FaceRecognitionStatusEnum.SUCCESS.getType());
//        } else {//识别历史
//            newFaceRecog.setPassed(FaceRecognitionStatusEnum.FAIL.getType());
//            newFaceRecog.getFailHistory().setItemStatus(UserModelItemStatusEnum.ADD.getType());
//        }
//        newUm.setAuthFaceRecognitions(Lists.newArrayList(newFaceRecog));
//        return Response.ok(true);
//    }


    /**
     * 芝麻认证 确认
     *
     * @param zmCreditConfirm
     * @param oldUm
     * @param newUm
     * @return
     */
    private Response<Boolean> checkZmConfirmStatus(ZMCreditConfirmRO zmCreditConfirm, UserAuthModel oldUm, UserAuthModel newUm,
                                                   Boolean authorized) {

        String userCode = UserHeadRequest.getThreadLocal().getUserCode();

        ZhimaCredit zmC = new ZhimaCredit();
        zmCreditConfirm.setUserCode(userCode);
        BeanUtils.copyProperties(zmCreditConfirm, zmC);
        zmC.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
        Customer customer = oldUm.getCustomer();
        ZhimaCredit oldZmc = oldUm.getZmCredit();
        //实名成功
        if (authorized && null != zmC.getOpenId()) {
            if (null == customer) {
                //根据身份证查询
                customer = userAuthFactory.getCustomerByIdentityNo(zmCreditConfirm.getIdentityNo());
            }
            if (null == customer) {
                customer = new Customer();
                customer.setUserCode(userCode);
                customer.setCustomerCode(userCode);
                customer.setName(zmCreditConfirm.getUserName());
                customer.setIdentityNo(zmCreditConfirm.getIdentityNo());
                customer.setCustomerCode(userCode);
                newUm.setCustomer(customer);
            }
            if (null != customer
                    && !(customer.getIdentityNo().equals(zmC.getIdentityNo())
                    && customer.getName().equals(zmC.getUserName()))) {
                return Response.error(UserStateCode.USER_REALNAME_NOT_MATCH_WITH_PRE);
            }
        }
        if (oldZmc.getAuthorized()) {
            return Response.error(UserStateCode.USER_AUTH_ZM_ALREADY_AUTHORIZED);
        }
        zmC.setId(oldZmc.getId());
        zmC.setStatus(authorized ? ZmCreditStatusEnum.SUCCESS.getType() : ZmCreditStatusEnum.FAIL.getType());
        newUm.setZmCredit(zmC);
        return Response.ok(true);
    }

    /**
     * 运营商认证
     * 维护一条有效的（多余的删除）
     *
     * @param carrierAuthSubmit
     * @param oldUm
     * @param newUm
     * @return
     */
    private Response<UserAuthSubmitRspRO> checkCarrierStatus(CarrierAuthSubmitRO carrierAuthSubmit, UserAuthModel oldUm,
                                                             UserAuthModel newUm) {
        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
        UserAuthCarrier newUc = new UserAuthCarrier();
        carrierAuthSubmit.setUserCode(userCode);
        BeanUtils.copyProperties(carrierAuthSubmit, newUc);

        UserAuthCarrier oldUc = oldUm.getUserAuthCarrier();
        newUc.setStatus(UserAuthStatusEnum.INIT.getStatus());
        if (null != oldUc) {
            newUc.setId(oldUc.getId());
            newUc.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
        } else {
            newUc.setItemStatus(UserModelItemStatusEnum.ADD.getType());
        }

        newUm.setUserAuthCarrier(newUc);

        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
        result.setUserCode(userCode);
        result.setBiz(biz);
        result.setAppCode(appCode);
        result.setSuccess(true);
        result.setAuthType(CreditAuthTypeEnum.TAOBAO.getType());
        return Response.ok(result);

    }

    /**
     * 淘宝认证
     * 维护一条(可重复覆盖认证)
     *
     * @param taobaoAuthSubmit
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<UserAuthSubmitRspRO> checkTaobaoStatus(TaobaoAuthSubmitRO taobaoAuthSubmit, UserAuthModel oldUm,
//                                                            UserAuthModel newUm) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//
//        UserAuthTaobao newUa = new UserAuthTaobao();
//        taobaoAuthSubmit.setUserCode(userCode);
//        BeanUtils.copyProperties(taobaoAuthSubmit, newUa);
//
//        UserAuthTaobao oldUa = oldUm.getAuthTaobao();
//        Integer maxDailyAuthTaobaoTime = userConfigService.queryMaxDailyAuthTaobaoTime(appCode, biz);
//        //获取今日支付宝认证次数
//        Integer userTaobaoTime = redisUtils.getObject("USER_AUTH_TAOBAO_DAILY_TIME" + userCode, Integer.class);
//        //人脸识别超过限制
//        if (null != userTaobaoTime && userTaobaoTime >= maxDailyAuthTaobaoTime) {
//            return Response.error(UserStateCode.USER_AUTH_TAOBAO_OVER_TIME);
//        }
//        newUa.setStatus(UserAuthStatusEnum.INIT.getStatus());
//        //设置更新状态
//        if (null == oldUa) {
//            newUa.setItemStatus(UserModelItemStatusEnum.ADD.getType());
//        } else {
//            newUa.setId(oldUa.getId());
//            newUa.setItemStatus(UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType());
//        }
//        redisUtils.incrBy("USER_AUTH_TAOBAO_DAILY_TIME" + userCode, 1, DateUtil.getDiffDayTime(new Date()));
//        newUm.setAuthTaobao(newUa);
//
//        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
//        result.setUserCode(userCode);
//        result.setBiz(biz);
//        result.setAppCode(appCode);
//        result.setSuccess(true);
//        result.setAuthType(CreditAuthTypeEnum.TAOBAO.getType());
//        return Response.ok(result);
//    }

    /**
     * 支付宝认证
     * 维护一条(可重复覆盖认证)
     *
     * @param alipayAuthSubmit
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<UserAuthSubmitRspRO> checkAlipayStatus(AlipayAuthSubmitRO alipayAuthSubmit, UserAuthModel oldUm, UserAuthModel newUm) {
//
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//
//        UserAuthAlipay newUa = new UserAuthAlipay();
//        alipayAuthSubmit.setUserCode(userCode);
//        BeanUtils.copyProperties(alipayAuthSubmit, newUa);
//
//        UserAuthAlipay oldUa = oldUm.getAuthAlipay();
//        Integer maxDailyAlipayTime = userConfigService.queryMaxDailyAuthAlipayTime(appCode, biz);
//        //获取今日支付宝认证次数
//        Integer userAlipayTime = redisUtils.getObject("USER_AUTH_ALIPAY_DAILY_TIME" + userCode, Integer.class);
//        //支付宝认证超过限制
//        if (null != userAlipayTime && userAlipayTime >= maxDailyAlipayTime) {
//            return Response.error(UserStateCode.USER_AUTH_ALIPAY_OVER_TIME);
//        }
//        newUa.setStatus(UserAuthStatusEnum.INIT.getStatus());
//        //设置更新状态
//        if (null == oldUa) {
//            newUa.setItemStatus(UserModelItemStatusEnum.ADD.getType());
//        } else {
//            newUa.setId(oldUa.getId());
//            newUa.setItemStatus(UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType());
//        }
//        redisUtils.incrBy("USER_AUTH_ALIPAY_DAILY_TIME" + userCode, 1, DateUtil.getDiffDayTime(new Date()));
//        newUm.setAuthAlipay(newUa);
//
//        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
//        result.setUserCode(userCode);
//        result.setBiz(biz);
//        result.setAppCode(appCode);
//        result.setSuccess(true);
//        result.setAuthType(CreditAuthTypeEnum.ALIPAY.getType());
//        return Response.ok(result);
//    }

    /**
     * 人脸识别
     *
     * @param faceRecognitionSubmit
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<UserAuthSubmitRspRO> checkFaceRecognitionStatus(FaceRecognitionSubmitRO faceRecognitionSubmit,
//                                                                     UserAuthModel oldUm, UserAuthModel newUm) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//        UserAuthFaceRecognition newFaceRecog = new UserAuthFaceRecognition();
//        faceRecognitionSubmit.setUserCode(userCode);
//        BeanUtils.copyProperties(faceRecognitionSubmit, newFaceRecog);
//        //查询是否处于人脸识别冷冻
//        Response<Boolean> isFrozenResponse = userFrozenApplication.isFrozen(userCode,
//                FrozenCodeEnum.FACE_RECONGNITION, null);
//        if (isFrozenResponse.isSuccess() && isFrozenResponse.getData()) {
//            return Response.error(UserStateCode.USER_FROZEN_FACE);
//        }
//        //查询该用户每天可人脸识别总次数
//        Integer maxDailyAuthFaceTime = userConfigService.queryMaxDailyAuthFaceTime(appCode, biz);
//        Integer userFaceTime = redisUtils.getObject("USER_AUTH_FACE_DAILY_TIME" + userCode, Integer.class);
//        //人脸识别超过限制
//        if (null != userFaceTime && userFaceTime >= maxDailyAuthFaceTime) {
//            return Response.error(UserStateCode.USER_AUTH_FACE_OVER_TIME);
//        }
//        //detail
//        UserAuthFaceRecognitionDetail detail = new UserAuthFaceRecognitionDetail();
//        detail.setUserCode(userCode);
//        detail.setFrontDetail(faceRecognitionSubmit.getFrontDetail());
//        detail.setFaceDetail(faceRecognitionSubmit.getFaceDetail());
//        detail.setBackDetail(faceRecognitionSubmit.getBackDetail());
//        newFaceRecog.setDetail(detail);
//        newFaceRecog.setPassed(FaceRecognitionStatusEnum.INIT.getType());
//        newFaceRecog.setItemStatus(UserModelItemStatusEnum.ADD.getType());
//        newUm.setAuthFaceRecognitions(Lists.newArrayList(newFaceRecog));
//        redisUtils.incrBy("USER_AUTH_FACE_DAILY_TIME" + userCode, 1, DateUtil.getDiffDayTime(new Date()));
//        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
//        result.setUserCode(userCode);
//        result.setBiz(biz);
//        result.setAppCode(appCode);
//        result.setSuccess(true);
//        result.setAuthType(CreditAuthTypeEnum.FACE.getType());
//        return Response.ok();
//    }

    /**
     * 芝麻状态校验（预提交）
     * 芝麻数据只维护一条
     *
     * @param zmCreditSubmit
     * @param oldUm
     * @param newUm
     */
    private Response<UserAuthSubmitRspRO> checkZmStatus(ZMCreditSubmitRO zmCreditSubmit, UserAuthModel oldUm, UserAuthModel newUm) {
        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
        ZhimaCredit newZmCredit = new ZhimaCredit();
        zmCreditSubmit.setUserCode(userCode);
        BeanUtils.copyProperties(zmCreditSubmit, newZmCredit);
        ZhimaCredit oldZmcredit = oldUm.getZmCredit();
        newZmCredit.setStatus(ZmCreditStatusEnum.INIT.getType());
        if (null == oldZmcredit) {
            newZmCredit.setItemStatus(UserModelItemStatusEnum.ADD.getType());
        } else if (!oldZmcredit.getAuthorized()) {
            newZmCredit.setId(oldZmcredit.getId());
            newZmCredit.setItemStatus(UserModelItemStatusEnum.UPDATE.getType());
        } else {
            return Response.error(UserStateCode.USER_AUTH_ZM_ALREADY_AUTHORIZED);
        }
        newUm.setZmCredit(newZmCredit);

        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
        result.setUserCode(userCode);
        result.setBiz(biz);
        result.setAppCode(appCode);
        result.setSuccess(true);
        result.setAuthType(CreditAuthTypeEnum.ZM.getType());
        return Response.ok(result);
    }

    /**
     * 信用卡认证提交
     *
     * @param creditCardSubmit
     * @param oldUm
     * @param newUm
     * @return
     */
//    private Response<UserAuthSubmitRspRO> checkCreditCardStatus(CreditCardSubmitRO creditCardSubmit, UserAuthModel oldUm,
//                                                                UserAuthModel newUm) {
//        String userCode = UserHeadRequest.getThreadLocal().getUserCode();
//        String appCode = UserHeadRequest.getThreadLocal().getAppCode();
//        Integer biz = UserHeadRequest.getThreadLocal().getBiz();
//
//        CreditCard newCc = new CreditCard();
//        newCc.setUserCode(userCode);
//        convertCreditCardRO2Model(creditCardSubmit, newCc);
//
//        List<CreditCard> creditCards = oldUm.getCreditCards();
//        Integer maxDailyAlipayTime = userConfigService.queryMaxDailyCreditCardTime(appCode, biz);
//        //获取今日支付宝认证次数
//        Integer userAlipayTime = redisUtils.getObject("USER_AUTH_CREDITCARD_DAILY_TIME" + userCode, Integer.class);
//        //信用卡认证超过限制
//        if (null != userAlipayTime && userAlipayTime >= maxDailyAlipayTime) {
//            return Response.error(UserStateCode.USER_AUTH_CREDITCARD_OVER_TIME);
//        }
//        newCc.setStatus(UserAuthStatusEnum.INIT.getStatus());
//        CreditCard oldUa = null;
//        if (CollectionUtils.isNotEmpty(creditCards)) {
//            for (CreditCard cc : creditCards) {
//                if (cc.getBankKey().equals(creditCardSubmit.getBankKey())) {
//                    oldUa = cc;
//                }
//            }
//        }
//        //设置更新状态
//        if (null == oldUa) {
//            newCc.setItemStatus(UserModelItemStatusEnum.ADD.getType());
//        } else {
//            newCc.setId(oldUa.getId());
//            newCc.setItemStatus(UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType());
//        }
//        redisUtils.incrBy("USER_AUTH_CREDITCARD_DAILY_TIME" + userCode, 1, DateUtil.getDiffDayTime(new Date()));
//        newUm.setCreditCards(Lists.newArrayList(newCc));
//
//        UserAuthSubmitRspRO result = new UserAuthSubmitRspRO();
//        result.setUserCode(userCode);
//        result.setBiz(biz);
//        result.setAppCode(appCode);
//        result.setSuccess(true);
//        result.setAuthType(CreditAuthTypeEnum.CREDIT_CARD.getType());
//        return Response.ok(result);
//
//    }

    /**
     * O2O
     *
     * @param creditCardSubmit
     * @param newCc
     */
    private void convertCreditCardRO2Model(CreditCardSubmitRO creditCardSubmit, CreditCard newCc) {
        newCc.setBankName(creditCardSubmit.getBankName());
        newCc.setBankKey(creditCardSubmit.getBankKey());
        newCc.setTaskId(creditCardSubmit.getTaskId());
        CreditCardAccount account = new CreditCardAccount();
        BeanUtils.copyProperties(creditCardSubmit.getAccount(), account);
        newCc.setAccount(account);
    }

    /**
     * 取消认证
     *
     * @param cancelAuth
     * @return
     */
    public Response<Boolean> cancelAuth(UserCancelAuthRO cancelAuth) {
        //加载模型
        UserAuthModel oldUm = new UserAuthModel();
        oldUm.setUserCode(cancelAuth.getUserCode());
        userAuthFactory.load(oldUm);

        UserAuthModel newUm = new UserAuthModel();
        newUm.setUserCode(cancelAuth.getUserCode());
        CreditAuthTypeEnum creditAuthType = CreditAuthTypeEnum.getEnumByType(cancelAuth.getAuthType());
        switch (creditAuthType) {
            case ZM:
                ZhimaCredit zmCredit = oldUm.getZmCredit();
                if (null == zmCredit || !zmCredit.getAuthorized()) {
                    return Response.error(UserStateCode.USER_AUTH_ZM_NOT_EXISTS);
                }
                zmCredit.setItemStatus(UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType());
                newUm.setZmCredit(zmCredit);
                break;
            case CREDIT_CARD:
                CreditCardCancelRO current = cancelAuth.getCreditCardCancel();
                List<CreditCard> creditCards = oldUm.getCreditCards();
                CreditCard creditCard = null;
                if (CollectionUtils.isEmpty(creditCards)) {
                    return Response.error(UserStateCode.USER_AUTH_CREDITCARD_NOT_EXISTS);
                }
                for (CreditCard cc : creditCards) {
                    if (cc.getBankKey().equals(current.getBankKey())) {
                        creditCard = cc;
                    }
                }
                if (null == creditCard) {
                    return Response.error(UserStateCode.USER_AUTH_CREDITCARD_NOT_EXISTS);
                }
                creditCard.setItemStatus(UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType());
                creditCard.setStatus(UserAuthStatusEnum.CANCEL.getStatus());
                newUm.setCreditCards(Lists.newArrayList(creditCard));
                break;
            default:
                break;
        }
        //存储数据
        userAuthFactory.store(newUm);
        return Response.ok(true);
    }


}
